const router = require('koa-router')()
const fs = require('fs')
const path = require('path');
const tool=require('../tool/tool');
var BaseRequest=require('../mongodb/baserequest.js');
var Model=new BaseRequest('new');


router.prefix('/api/new');


router.use(async(ctx,next)=>{
  ctx.response.type='json';
  console.log(ctx.session.user)
  await next();
})
router.post('/upload',function(ctx,next){
    console.log(ctx.request.picture)
    ctx.body={
        errorCode:0,data:ctx.request.picture
    }
})
router.post('/add',async function(ctx,next){
    var req=ctx.request;
    //console.log(req.body);
    var t=req.body;
    
    t.userid=ctx.session.user && ctx.session.user._id;
    console.log(t);
    var result=await Model.save(t);
    ctx.body=result;
});
router.post('/amount',async function(ctx,next){
    var req=ctx.request;
    console.log(req.body)
    var result=await Model.updateOne({_id:req.body.id},{
        '$inc':{amount:1}
    })
    ctx.body=result;
})
router.post('/praisenumber',async function(ctx,next){
    var req=ctx.request;
    console.log(req.body)
    var result=await Model.updateOne({_id:req.body.id},{
        '$inc':{praisenumber:1}
    })
    ctx.body=result;
})
router.post('/commentnumber',async function(ctx,next){
    var req=ctx.request;
    console.log(req.body)
    var result=await Model.updateOne({_id:req.body.id},{
        '$inc':{commentnumber:1}
    })
    ctx.body=result;
})
router.post('/list/:id',async function(ctx,next){
    
    var result =await Model.model._findById(
        ctx.params.id,{},{},['userid','tags','topicid'])
    var u=await Model.updateOne({_id:ctx.params.id},{
        '$inc':{amount:1}
    })
    ctx.body=result;
})
router.post('/list',async function(ctx,next){
    var req=ctx.request;
    
    // var result=await Model.queryPagePopulatetwo({},
    //     {page:req.body.currentPage,limit:req.body.pageSize},
    //     {path:'topicid',select:'_id title',module:'topic'},
    //     'tags')
    
    var result=await Model.model._findPage({},
        {page:req.body.currentPage,limit:req.body.pageSize},
        {path:'topicid',select:'_id title',module:'topic'},
        'tags',{path:'userid',select:'name answernumber contentnumber follownumber imgurl'})
    //console.log(result);
    ctx.body=result;
})
router.post('/update',async function(ctx,next){
    var req=ctx.request;
    var obj=req.body;
    delete obj.id;
    var result=await Model.update({_id:req.body._id},obj);
    ctx.body=result;
})
router.post('/remove/:id',async function(ctx,next){
    var req=ctx
    console.log(req.params.id);
    var result=await Model.findOneAndRemove({_id:req.params.id});
    
    ctx.body=result;
  
})

module.exports = router;

